class Router {
    constructor() {
        this.routes = new Map();
        this.currentComponent = null;
        
        // Handle browser back/forward buttons
        window.addEventListener('popstate', () => {
            this.handleRoute(window.location.pathname);
        });
    }

    // Register a route
    route(path, component) {
        this.routes.set(path, component);
    }

    // Navigate to a new route
    push(path) {
        window.history.pushState({}, '', path);
        this.handleRoute(path);
    }

    // Handle route changes
    handleRoute(pathname) {
        const component = this.routes.get(pathname);
        if (component) {
            this.currentComponent = component;
            this.render();
        }
    }

    // Initial route setup
    start() {
        this.handleRoute(window.location.pathname);
    }

    // Render the current component
    render() {
        const root = document.getElementById('root');
        if (root && this.currentComponent) {
            root.innerHTML = '';
            root.appendChild(this.currentComponent());
        }
    }
}

// Link component for navigation
class Link {
    constructor(router) {
        this.router = router;
    }

    create(to, text) {
        const link = document.createElement('a');
        link.href = to;
        link.textContent = text;
        link.addEventListener('click', (e) => {
            e.preventDefault();
            this.router.push(to);
        });
        return link;
    }
}

// Example usage:
const router = new Router();
const link = new Link(router);

// Define routes
router.route('/', () => {
    const element = document.createElement('div');
    element.innerHTML = '<h1>Home Page</h1>';
    return element;
});

router.route('/about', () => {
    const element = document.createElement('div');
    element.innerHTML = '<h1>About Page</h1>';
    return element;
});

// Start the router
router.start();